package ru.spb.osll.myfit.fixtures;

import java.util.LinkedList;
import java.util.Vector;

import ru.spb.osll.myfit.common.GlobalContainer;
import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.fixtures.base.MyFitTableFixture;
import ru.spb.osll.myfit.server.FitServiceImpl;
import ru.spb.osll.myfit.util.Pair;
import fit.Parse;

public class CreatePageFixture extends MyFitTableFixture {
	@Override
	public void doStaticTable() {
		Page page = createPage();
//		System.out.println(TableUtils.pageToString(page));
		FitServiceImpl fitService = GlobalContainer.instance().getFitService();
		fitService.savePage("", page);
	}

	private Vector<TableCell> createTableLine(LinkedList<Pair<String, Parse>> line) {
		Vector<TableCell> tableLine = new Vector<TableCell>();
		for(Pair<String, Parse> elem : line) {
			tableLine.add(new TableCell(elem.getFirst()));
			right(elem.getSecond());
		}
		return tableLine;
	}
	
	private Page createPage() {
		Page page = new Page();
		Table table = new Table();
		for(LinkedList<Pair<String, Parse>> line : getCells()) {
			Vector<TableCell> tableLine = createTableLine(line);
			if (!tableLine.isEmpty()) {
				table.addLine(tableLine);
			} else {
				if (!table.isEmpty()) {
					page.getElements().add(table);
					table = new Table();
				}
			}
		}
		if (!table.isEmpty()) {
			page.getElements().add(table);
			table = new Table();
		}

		return page;
	}
	
	public static String[] getTestTableTemplates() {
		return new String[] { "|create page|\n||\n" };
	}
}
